/**
 * 
 */
package net.xfok.mail.sender;

import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import android.util.Log;

/**
 * @author howard
 * 
 */
public class GMailSender extends MailSender{
	
	private final static String TAG="GMailSender";
	
	private final static String smtpHost = "smtp.gmail.com";
	private final static String smtpPort = "465";
	private final static String smtpAuth = "true";
	private final static String popHost = "pop.gmail.com";
	private final static String popPort = "995";
	
	private Multipart mp;
	
	public GMailSender(String username, String password) {
		super(smtpHost, username, password);
	}
	
	private GMailSender(String smtp, String username, String password) {
		super(smtp, username, password);
	}
	
	public void send(String to, String subject, String body) {
		// TODO Auto-generated method stub
		send(username ,to, subject, body);
	}

	public void send(String from,String to, String subject,String body) {
		try{
			// Get a Properties object
			Properties props = System.getProperties();
			setSmtpProps(props);
			Session session = Session.getDefaultInstance(props,
					new Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(username, password);
						}
					});
			// -- Create a new message --
			Message msg = new MimeMessage(session);
			// -- Set the FROM and TO fields --
			msg.setFrom(new InternetAddress(from));
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,
					false));
			msg.setSubject(subject);
			msg.setText(body);
			msg.setSentDate(new Date());
			Transport.send(msg);
			Log.i(TAG, "Send sucess!");
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void sendWithAffix(String to, String subject,
			String html, String affix){
		try{	
			// Get a Properties object
			Properties props = System.getProperties();
			setSmtpProps(props);
			Session session = Session.getDefaultInstance(props,
					new Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(username, password);
						}
					});
			// -- Create a new message --
			Message msg = new MimeMessage(session);
			// -- Set the FROM and TO fields --
			msg.setFrom(new InternetAddress(username));
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,
					false));
			msg.setSubject(subject);
			mp = new MimeMultipart();
			BodyPart bp = new MimeBodyPart();
			bp.setContent(
					"<meta http-equiv=Content-Type content=text/html; charset=gb2312>"
							+ html, "text/html;charset=UTF-8");
			mp.addBodyPart(bp);
			BodyPart bp1 = new MimeBodyPart();
			FileDataSource fileds = new FileDataSource(affix);
			bp1.setDataHandler(new DataHandler(fileds));
			bp1.setFileName(fileds.getName());
			mp.addBodyPart(bp1);
			msg.setSentDate(new Date());
			msg.setContent(mp);
			Transport.send(msg);
			Log.i(TAG, "Send sucess!");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public Message[] fetch(){
		Message[] messages=null;
		try{	
			// Get a Properties object
			Properties props = System.getProperties();
			setPop3Props(props);
			// 以下步骤跟一般的JavaMail操作相同
			Session session = Session.getDefaultInstance(props, null);
			// 请将红色部分对应替换成你的邮箱帐号和密码
			URLName urln = new URLName("pop3", popHost, Integer.parseInt(popPort),
					null, username, password);
			Store store = session.getStore(urln);
			Folder inbox = null;
			try {
				store.connect();
				inbox = store.getFolder("INBOX");
				inbox.open(Folder.READ_ONLY);
				FetchProfile profile = new FetchProfile();
				profile.add(FetchProfile.Item.ENVELOPE);
				messages = inbox.getMessages();
				inbox.fetch(messages, profile);
			} finally {
				try {
					inbox.close(false);
				} catch (Exception e) {
				}
				try {
					store.close();
				} catch (Exception e) {
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return messages;
	}

	private void setSmtpProps(Properties props){
		Security.addProvider(new JSSEProvider());
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		props.setProperty("mail.smtp.host", smtpHost);
		props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
		props.setProperty("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.port", smtpPort);
		props.setProperty("mail.smtp.socketFactory.port", smtpPort);
		props.put("mail.smtp.auth", smtpAuth);
	}
	
	private void setPop3Props(Properties props){
		Security.addProvider(new JSSEProvider());
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
		props.setProperty("mail.pop3.socketFactory.fallback", "false");
		props.setProperty("mail.pop3.port", popPort);
		props.setProperty("mail.pop3.socketFactory.port", popPort);
	}
	
	protected static String decodeText(String text)
			throws UnsupportedEncodingException {
		if (text == null)
			return null;
		if (text.startsWith("=?GB") || text.startsWith("=?gb"))
			text = MimeUtility.decodeText(text);
		else
			text = new String(text.getBytes("ISO8859_1"));
		return text;
	}

}
